const {
    _decodeCont
} = require("./decodeCont.js")
const https = require('https');
const fs = require('fs');

// 章节请求
const path = "/pcapi/chapter/contentfree/"
const options = {
    hostname: 'c13.shuqireader.com',
    path: path + "?bookId=8989304&chapterId=2247912&ut=1734715263&num=1&ver=1&aut=1735195390&sign=0db4045fc1a05529fc0d1ef137cc1e6b",
    method: 'GET', // 请求方法
    headers: {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0"
    }
};

// 全文请求
const options2 = {
    hostname: 'www.shuqi.com',
    path: "/reader" + "?bid=8989304",
    method: 'GET', // 请求方法
    headers: {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0"
    }
};
let bookName = ""
let content = []
let titles = []
const setFile = () => {
    // 写入文件的路径
    const filePath = `./${bookName}.txt`;
    const fileContent = []
    titles.forEach((d, i) => {
        fileContent.push(d)
        fileContent.push(content[i])
    })
    let fileContent2 = fileContent.join("\r")
    // 将内容写入文件

    if (content[0]) {
        fs.writeFile(filePath, fileContent2, (err) => {
            if (err) {
                console.error('写入文件时发生错误:', err);
            } else {
                console.log('文件写入成功');
            }
        });
    }
}
// 创建请求
const getFn = (item) => {
    return new Promise((resolve, reject) => {
        options.path = path + item.contUrlSuffix
        // 创建请求
        const req = https.request(options, (res) => {

            let responseData = '';
            res.on('data', (chunk) => {
                responseData += chunk;
            });

            res.on('end', () => {
                //处理
                let ChapterContent = _decodeCont(JSON.parse(responseData).ChapterContent)
                if (!ChapterContent) {
                    reject(false);
                }
                let str = ChapterContent.replaceAll("<br/>", "\r")
                if (str) {
                    titles.push(item.chapterName)
                    console.log(item.chapterName)
                    content.push(str)
                    resolve(true)
                }
            });
        });

        req.on('error', (error) => {
            setFile()
            console.error('请求出错:', error.message);
        });

        req.end(); // 结束请求
    })

}
const req2 = https.request(options2, (res) => {
    let responseData = '';
    res.on('data', (chunk) => {
        responseData += chunk;
    });
    res.on('end', async () => {

        let regex = /<i class="page-data js-dataChapters">(.*?)<\/i>/gs;
        let str = responseData.match(regex)[0]

        str = str.replace(`<i class="page-data js-dataChapters">`, '')
        str = str.replace(`</i>`, '')
        str = str.replaceAll('&quot;', `"`)
        str = str.replaceAll('&amp;', `&`)

        let json = JSON.parse(str)
        //小说名字,全部内容  
        let volumeList = json.chapterList[0].volumeList
        let regex2 = /[^\u4e00-\u9fa5]/g; // 匹配非中文字符
        bookName = json.bookName.replace(regex2, "")
        //提取章节
        // await getFn(volumeList[0])
        for (const item of volumeList) {
            try {
                await getFn(item)
            } catch (error) {
                break; // 当请求失败时，跳出循环
            }

        }
        setFile()
    });
});
req2.end()